import { Inject, Injectable, Logger } from '@nestjs/common'
import { CommandsService } from './commands.service'
import { PingCommand } from '../commands/ping.command'
import { EvalCommand } from '../commands/eval.command'
import { BotLeftSupportDto, BOT_CLIENT, BOT_CLIENT_BOT_LEFT_SUPPORT } from '@boticord/bot-client'
import { ClientProxy } from '@nestjs/microservices'
import { ConfigService } from '@nestjs/config'
import { DiscordooService } from '@boticord/discordoo'

@Injectable()
export class BotService {
  private readonly logger = new Logger(BotService.name)

  constructor(
    private readonly commands: CommandsService,
    @Inject(BOT_CLIENT) private readonly bot: ClientProxy,
    private readonly config: ConfigService,
    private readonly discordoo: DiscordooService,
  ) {
    this.discordoo.client.on('ready', this.ready.bind(this))

    // you need to register all commands here to make them available to users
    // this.commands.register(
    //   new PingCommand(),
    //   new EvalCommand(),
    // )

    // this will call the handle method of the commands service, which will call the handle method of the command
    this.discordoo.client.on('messageCreate', ctx => {
      return this.commands.handle(ctx, this.discordoo.client)
    })

    this.discordoo.client.on('guildMemberRemove', async (context) => {
      if (context.guildId !== this.config.get('QUEUE_SERVER')) return

      const user = await this.discordoo.client.users.cache.get(context.userId)
      if (!user || !user?.bot) return

      await this.bot.emit<BotLeftSupportDto>(BOT_CLIENT_BOT_LEFT_SUPPORT, { id: context.userId })
    })
  }

  ready() {
    this.logger.log('Bot is ready!')
  }
}
